# -*- coding: utf-8 -*-
# @Time    :2022/2/28 21:22
# @AUTHOR  :MORAN
# @Email   :moran@maqu.com
# @File    :serializers.py
# @Software:PyCharm
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from community.models import Article, Comment


class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)

    class Meta:
        model = Article
        exclude = ['is_delete']


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = SerializerMethodField()

    class Meta:
        model = Comment
        fields = "__all__"

    def get_reply_username(self, comment):
        try:
            user = Comment.objects.get(id=comment.reply_comment).user
            return user.first_name
        except Exception as e:
            print(e)


class CommentHandleSerializer(ModelSerializer):
    sonComment = SerializerMethodField()
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)

    class Meta:
        model = Comment
        fields = '__all__'

    def get_sonComment(self, comment):
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()
        return data
